// 统一的HTTP请求工具

import { getBaseURL, REQUEST_TIMEOUT, REQUEST_HEADERS } from '@/config/api'

// 请求拦截器 - 添加token等通用参数
const requestInterceptor = (config) => {
  // 添加基础URL
  if (!config.url.startsWith('http')) {
    config.url = getBaseURL() + config.url
  }

  // 添加请求头
  config.header = {
    ...REQUEST_HEADERS,
    ...config.header
  }

  // 添加token
  const token = uni.getStorageSync('token')
  if (token) {
    config.header['Authorization'] = `Bearer ${token}`
  }

  // 添加超时时间
  config.timeout = config.timeout || REQUEST_TIMEOUT

  // 参数名映射 - 将前端参数名映射为后端期望的参数名
  if (config.data) {
    config.data = mapRequestFields(config.data)
  }
  if (config.params) {
    config.params = mapRequestFields(config.params)
  }

  return config
}

// 请求参数映射函数
const mapRequestFields = (data) => {
  if (!data) return data
  
  // 如果是数组，递归处理每个元素
  if (Array.isArray(data)) {
    return data.map(item => mapRequestFields(item))
  }
  
  // 如果是对象，处理字段映射
  if (typeof data === 'object') {
    const mapped = {}
    
    for (const [key, value] of Object.entries(data)) {
      let newKey = key
      let newValue = value
      
      // 字段名映射规则 - 前端参数名 -> 后端参数名
      switch (key) {
        case 'pageSize':
          newKey = 'page_size'
          break
        case 'categoryId':
          newKey = 'category_id'
          break
        case 'goodsId':
          newKey = 'goods_id'
          break
        case 'specId':
          newKey = 'spec_id'
          break
        case 'orderId':
          newKey = 'order_id'
          break
        case 'addressId':
          newKey = 'address_id'
          break
        case 'userId':
          newKey = 'user_id'
          break
        case 'createTime':
          newKey = 'create_time'
          break
        case 'updateTime':
          newKey = 'update_time'
          break
        case 'goodsName':
          newKey = 'goods_name'
          break
        case 'specName':
          newKey = 'spec_name'
          break
        case 'retailPrice':
          newKey = 'retail_price'
          break
        case 'marketPrice':
          newKey = 'market_price'
          break
        case 'salesQuantity':
          newKey = 'sales_quantity'
          break
        case 'isDefault':
          newKey = 'is_default'
          break
        case 'receiverName':
          newKey = 'receiver_name'
          break
        case 'receiverPhone':
          newKey = 'receiver_phone'
          break
        case 'detailAddress':
          newKey = 'detail_address'
          break
        case 'postalCode':
          newKey = 'postal_code'
          break
        case 'addressTag':
          newKey = 'address_tag'
          break
        case 'paymentMethod':
          newKey = 'payment_method'
          break
        case 'shippingFee':
          newKey = 'shipping_fee'
          break
        case 'discountAmount':
          newKey = 'discount_amount'
          break
        case 'totalAmount':
          newKey = 'total_amount'
          break
        case 'finalAmount':
          newKey = 'final_amount'
          break
        case 'orderStatus':
          newKey = 'order_status'
          break
        case 'paymentStatus':
          newKey = 'payment_status'
          break
        case 'tradeNo':
          newKey = 'trade_no'
          break
        case 'customerName':
          newKey = 'customer_name'
          break
        case 'customerAvatar':
          newKey = 'customer_avatar'
          break
        case 'commentId':
          newKey = 'comment_id'
          break
        case 'replyContent':
          newKey = 'reply_content'
          break
        case 'brandName':
          newKey = 'brand_name'
          break
        case 'className':
          newKey = 'class_name'
          break
        case 'shortName':
          newKey = 'short_name'
          break
        case 'imgUrl':
          newKey = 'img_url'
          break
        case 'specBarcode':
          newKey = 'spec_barcode'
          break
        case 'originalPrice':
          newKey = 'original_price'
          break
        default:
          // 如果值也是对象或数组，递归处理
          if (typeof value === 'object' && value !== null) {
            newValue = mapRequestFields(value)
          }
      }
      
      mapped[newKey] = newValue
    }
    
    return mapped
  }
  
  return data
}

// 响应拦截器 - 统一处理响应
const responseInterceptor = (response) => {
  const { data, statusCode } = response
  // HTTP状态码检查
  if (statusCode !== 200) {
    // 特殊处理403错误
    if (statusCode === 403) {
      throw new Error('权限不足，请检查登录状态或联系管理员')
    }
    throw new Error(`HTTP ${statusCode}: 请求失败`)
  }

  // 业务状态码检查
  if (data.code !== undefined) {
    if (data.code === 200 || data.code === 0) {
      // 请求成功，进行字段名映射
      const mappedData = mapResponseFields(data)
      return mappedData
    } else if (data.code === 401) {
      // token过期或无效
      handleAuthError()
      throw new Error('登录已过期，请重新登录')
    } else {
      // 其他业务错误
      throw new Error(data.message || '请求失败')
    }
  }

  // 直接返回响应数据，进行字段名映射
  const mappedData = mapResponseFields(data)
  return mappedData
}

// 字段名映射函数
const mapResponseFields = (data) => {
  if (!data) return data
  
  // 如果是数组，递归处理每个元素
  if (Array.isArray(data)) {
    return data.map(item => mapResponseFields(item))
  }
  
  // 如果是对象，处理字段映射
  if (typeof data === 'object') {
    const mapped = {}
    
    for (const [key, value] of Object.entries(data)) {
      let newKey = key
      let newValue = value
      
      // 字段名映射规则
      switch (key) {
        case 'page_size':
          newKey = 'pageSize'
          break
        case 'category_id':
          newKey = 'categoryId'
          break
        case 'goods_id':
          newKey = 'goodsId'
          break
        case 'spec_id':
          newKey = 'specId'
          break
        case 'order_id':
          newKey = 'orderId'
          break
        case 'address_id':
          newKey = 'addressId'
          break
        case 'user_id':
          newKey = 'userId'
          break
        case 'create_time':
          newKey = 'createTime'
          break
        case 'update_time':
          newKey = 'updateTime'
          break
        case 'goods_name':
          newKey = 'goodsName'
          break
        case 'spec_name':
          newKey = 'specName'
          break
        case 'retail_price':
          newKey = 'retailPrice'
          break
        case 'market_price':
          newKey = 'marketPrice'
          break
        case 'sales_quantity':
          newKey = 'salesQuantity'
          break
        case 'is_default':
          newKey = 'isDefault'
          break
        case 'receiver_name':
          newKey = 'receiverName'
          break
        case 'receiver_phone':
          newKey = 'receiverPhone'
          break
        case 'detail_address':
          newKey = 'detailAddress'
          break
        case 'postal_code':
          newKey = 'postalCode'
          break
        case 'address_tag':
          newKey = 'addressTag'
          break
        case 'payment_method':
          newKey = 'paymentMethod'
          break
        case 'shipping_fee':
          newKey = 'shippingFee'
          break
        case 'discount_amount':
          newKey = 'discountAmount'
          break
        case 'total_amount':
          newKey = 'totalAmount'
          break
        case 'final_amount':
          newKey = 'finalAmount'
          break
        case 'order_status':
          newKey = 'orderStatus'
          break
        case 'payment_status':
          newKey = 'paymentStatus'
          break
        case 'trade_no':
          newKey = 'tradeNo'
          break
        case 'customer_name':
          newKey = 'customerName'
          break
        case 'customer_avatar':
          newKey = 'customerAvatar'
          break
        case 'comment_id':
          newKey = 'commentId'
          break
        case 'reply_content':
          newKey = 'replyContent'
          break
        case 'brand_name':
          newKey = 'brandName'
          break
        case 'class_name':
          newKey = 'className'
          break
        case 'short_name':
          newKey = 'shortName'
          break
        case 'img_url':
          newKey = 'imgUrl'
          break
        case 'spec_barcode':
          newKey = 'specBarcode'
          break
        case 'original_price':
          newKey = 'originalPrice'
          break
        default:
          // 如果值也是对象或数组，递归处理
          if (typeof value === 'object' && value !== null) {
            newValue = mapResponseFields(value)
          }
      }
      
      mapped[newKey] = newValue
    }
    
    return mapped
  }
  
  return data
}

// 处理认证错误
const handleAuthError = () => {
  // 清除本地存储的用户信息
  uni.removeStorageSync('userInfo')
  uni.removeStorageSync('token')
  uni.removeStorageSync('isLogin')

  // 跳转到登录页
  uni.showModal({
    title: '提示',
    content: '登录已过期，请重新登录',
    showCancel: false,
    success() {
      uni.reLaunch({
        url: '/pages/login/index'
      })
    }
  })
}

// 统一请求方法
const request = (config) => {
  return new Promise((resolve, reject) => {
    // 请求前拦截
    const finalConfig = requestInterceptor(config)

    // 发送请求
    uni.request({
      ...finalConfig,
      success: (response) => {
        try {
          // 响应拦截
          const result = responseInterceptor(response)
          resolve(result)
        } catch (error) {
          reject(error)
        }
      },
      fail: (error) => {
        let errorMessage = '网络请求失败'
        if (error.errMsg) {
          if (error.errMsg.includes('timeout')) {
            errorMessage = '请求超时，请检查网络连接'
          } else if (error.errMsg.includes('fail')) {
            errorMessage = '网络连接失败，请检查网络设置'
          }
        }
        
        reject(new Error(errorMessage))
      }
    })
  })
}

// GET请求
export const get = (url, params = {}, config = {}) => {
  return request({
    url,
    method: 'GET',
    data: params,
    ...config
  })
}

// POST请求
export const post = (url, data = {}, config = {}) => {
  return request({
    url,
    method: 'POST',
    data,
    ...config
  })
}

// PUT请求
export const put = (url, data = {}, config = {}) => {
  return request({
    url,
    method: 'PUT',
    data,
    ...config
  })
}

// DELETE请求
export const del = (url, params = {}, config = {}) => {
  return request({
    url,
    method: 'DELETE',
    data: params,
    ...config
  })
}

// 文件上传
export const upload = (url, filePath, formData = {}, config = {}) => {
  return new Promise((resolve, reject) => {
    // 添加token
    const token = uni.getStorageSync('token')
    const header = {
      ...config.header
    }
    if (token) {
      header['Authorization'] = `Bearer ${token}`
    }

    // 完整URL
    const fullUrl = url.startsWith('http') ? url : getBaseURL() + url
    uni.uploadFile({
      url: fullUrl,
      filePath,
      name: 'file',
      formData,
      header,
      success: (response) => {
        try {
          const data = JSON.parse(response.data)
          const result = responseInterceptor({ data, statusCode: response.statusCode })
          resolve(result)
        } catch (error) {
          reject(error)
        }
      },
      fail: (error) => {
        reject(new Error('文件上传失败'))
      }
    })
  })
}

// 下载文件
export const download = (url, config = {}) => {
  return new Promise((resolve, reject) => {
    // 添加token
    const token = uni.getStorageSync('token')
    const header = {
      ...config.header
    }
    if (token) {
      header['Authorization'] = `Bearer ${token}`
    }

    // 完整URL
    const fullUrl = url.startsWith('http') ? url : getBaseURL() + url

    uni.downloadFile({
      url: fullUrl,
      header,
      success: resolve,
      fail: (error) => {
        reject(new Error('文件下载失败'))
      }
    })
  })
}

// 默认导出
export default {
  request,
  get,
  post,
  put,
  del,
  upload,
  download
}    